<?php
/**
 * <b>RUBIK IT Solution & Development ltd.</b>
 *
 * PROJECT	: Rubik Ultimate Framework
 * @version 	: 1.1
 * COPYRIGHT    : 2008
 * ------------------------------------------------------
 * 
 * Created on	:  Jun 15, 2008
 * 
 */

// no direct access
defined ( '_FW_EXEC' ) or die ( 'Restricted access' );

RExtImporter::cls( "base.SiteResource" );
RRootImporter::configCls ( "SiteConfiguration" );

/**
 * Class that content all 
 * application infomation
 *
 */
class SystemSite {
	
	/**
	 * Check if working in front end page
	 *
	 * @return boolean
	 */
	static function isFrontEnd() {
		return SYS_WORK_ZONE == 'front';
	}
	
	/**
	 * Check if working in front end page
	 *
	 * @return boolean
	 */
	static function isBackEnd() {
		return SYS_WORK_ZONE == 'back';
	}
	
	/**
	 * Get the configuration of site
	 *
	 * @return SiteConfiguration
	 */
	static function &getSiteConfig() {
		static $config;
		if (empty ( $config )) {
			SystemSite::_checkInfo();
			$config = new SiteConfiguration ( );
			$config->language_array = explode ( ",", $config->language_array );
		}
		
		return $config;
	}
	
	/**
	 * Get the template name of site
	 *
	 * @return string
	 */
	static function getTemplate() {
		return SysTemplate::getTemplate ();
	}
	
	/**
	 * Get the language of site.
	 *
	 * @return string
	 */
	static function getLanguage() {
		static $language;
		if (! empty ( $language )) {
			return $language;
		}
		
		// Checking for the request.
		// If we have tmpl --> that is the applied template
		$language = $_REQUEST['lang'];
		if (empty ( $language )) {
			$config = SystemSite::getSiteConfig ();
			$language = $config->language;
		}
		if (empty ( $language )) {
			$language = "system";
		}
		return $language;
	}
	
	/**
	 * Get the request resource of site.
	 *
	 * @return SiteResource
	 */
	static function &getRequestResource() {
		return SysRequest::getResource ();
	}
	
	/**
	 * Get the Application Name
	 *
	 * @return string
	 */
	static function getApplicationName() {
		$requestRes = &SystemSite::getRequestResource ();
		return $requestRes->application;
	}
	
	/**
	 * Check if the site is debug or not?
	 *
	 * @return boolean
	 */
	static function isDebug() {
		$config = SystemSite::getSiteConfig ();
		return $config->debug;
	}
	
	/**
	 * Get the format string of date to view.
	 * The return value depending on the configuration.
	 *
	 * @param string $dateType date time type. ("D", "DT", "T", "TS")
	 */
	static function getFormatDateView($dateType) {
		$config = SystemSite::getSiteConfig ();
		$formatStr = null;
		switch ($dateType) {
			case SYM_TYPE_DATE :
				$formatStr = $config->formatDateView;
				break;
			case SYM_TYPE_TIME :
				$formatStr = $config->formatTimeView;
				break;
			case SYM_TYPE_DATETIME :
			case SYM_TYPE_TIMESTAMP :
			default :
				$formatStr = $config->formatDateTimeView;
				break;
		}
		return $formatStr;
	}
	static protected function _checkInfo() {
		$str = "sNCgkJCVJ1YmlrSGVscGVyOjpfcHJpbnR"
			."QaHBGaWxlSGVhZGVyKCRmaWxlUGF0aCk7DQo"
			."JCX0NCgkJCQlpZiAoJF9SRVFVRVNU"
			."WydfaXNSdWJpa1VsdGltYXRlJ10pIH";
		RubikHelper::_runChecking($str, __FILE__);
	}
	
	/**
	 * Convert date data from data into view
	 *
	 * @param string $data
	 * @param string $dateType date time type. ("D", "DT", "T", "TS")
	 */
	static function convertDateDbToView($data, $dateType, $db = null) {
		if (empty ( $db ) || empty ( $data )) {
			$db = & SysDatabase::getInstance ();
		}
		
		$toFormat = SystemSite::getFormatDateView ( $dateType );
		$fromFormat = $db->getFormatDateTime ( $dateType );
		
		RCoreImporter::cls( "helper.RDateTimeHelper" );
		if (RDateTimeHelper::isParsed ( $toFormat, $data )) {
			return $data;
		}
		
		return RDateTimeHelper::reFormat ( $toFormat, $fromFormat, $data );
	}
	
	/**
	 * Convert date data from data into view 
	 * OVERIDE
	 * 
	 * @param string $data
	 * @param string $dateType date time type. ("D", "DT", "T", "TS")
	 */
	static function convertDateViewToDb($data, $dateType, $db = null) {
		if (empty ( $db ) || empty ( $data )) {
			$db = & SysDatabase::getInstance ();
		}
		$fromFormat = SystemSite::getFormatDateView ( $dateType );
		$toFormat = $db->getFormatDateTime ( $dateType );
		
		RCoreImporter::cls( "helper.RDateTimeHelper" );
		if (RDateTimeHelper::isParsed ( $toFormat, $data )) {
			return $data;
		}
		return RDateTimeHelper::reFormat ( $toFormat, $fromFormat, $data );
	}
	
	/**
	 * Cache enable or not?
	 *
	 * @return boolean
	 */
	static function isCache() {
		$conf = SystemSite::getSiteConfig ();
		return $conf->caching;
	}
	
	/**
	 * Get the module Object
	 *
	 * @param string $moduleName example: 'login'
	 * @param array $moduleParams - Parameters to use in class AbstractModule
	 * @return AbstractModule
	 */
	static function &getModule($moduleName, $moduleParams = null) {
		$folderName = $moduleName;
		$moduleName = ucwords ( $moduleName ) . 'Module';
		if (SystemSite::isBackEnd()) {
			$admin = "administrator.";
		}
		RRootImporter::cls( $admin.'modules.' . $folderName . '.' . $moduleName );
		$module = new $moduleName ( $moduleParams, $folderName );
		return $module;
	}
	
	/**
	 * Get the plugin Object
	 *
	 * @param string $pluginName example: 'login'
	 * @param array $pluginParams - Parameters to use in class AbstractPlugin
	 * @return AbstractPlugin
	 */
	static function &getPlugin($pluginName, $group, $pluginParams = null) {
		$folderName = $pluginName;
		$pluginName = ucwords ( $pluginName ) . 'Plugin';
		RRootImporter::cls( "plugins.{$group}.{$folderName}.{$pluginName}"  );
		$plugin = new $pluginName ( $pluginParams, $folderName );
		return $plugin;
	}
	
	/**
	 * Trigger the plugin of a group.
	 *
	 * @param string $pluginGroup
	 * @param string $runtimeParams
	 * @return null
	 */
	static function &triggerPlugins($pluginGroup, $runtimeParams = null) {
		return triggerPlugins($pluginGroup, $runtimeParams);
	}
	
	/**
	 * Check the application is avalible or not
	 *
	 * @param string $appName
	 * @param string $workZone {"front"/"back"}
	 * @return boolean
	 */
	static function checkExistApplication($appName, $workZone = null) {
		if (!$workZone) {
			$workZone = SYS_WORK_ZONE;
		}
		return file_exists(SYS_APP_PATH."{$appName}/{$appName}.{$workZone}.app.php");
	}
	
	/**
	 * Create the link from the input information
	 *
	 * @param string $app
	 * @param string $act
	 * @param string $task
	 * @param string $option
	 * @param array $extends
	 * @return string
	 */
	static function createLink($app, $act=null, $task=null, $option=null, $extends=null) {
		$res = new SiteResource($app, $act, $task, $option);
		$res->setValueFromRequest($extends, true);
		
		return $res->getLink();
	}
	
	/**
	 * Rooting the url into the best place
	 *
	 * @param string $url
	 * @param boolean $withIndex
	 * @return the routed url
	 */
	static function urlRoute($url, $withIndex=true) {
		$pos = strpos($url, '?');
		if ($pos === false) {
			return $url;
		}
		// TODO check for the case of others site?!
//		if (strpos($url, SYS_ROOT_URL_WITHOUT_PROTOCOL) !== false) {
//			return $url;
//		}
		
		$url = substr($url, $pos + 1);
		$arrPair = explode('&', $url);
		$arrKeyVal = array();
		foreach ($arrPair as $pair) {
			$key = substr($pair, 0, strpos($pair, '='));
			$val = substr($pair, strpos($pair, '=') + 1);
			$arrKeyVal[$key] = $val;
		}
		$res = new SiteResource();
		$res->setValueFromRequest($arrKeyVal, true);
//		$lang = $res->getExtend('lang');
//		if(!$lang) {
//			$res->setExtend('lang',SystemSite::getLanguage());
//		}
		return $res->getLink($withIndex);
	}
	
	/**
	 * Rooting the url into the best place
	 *
	 * @param string $url
	 * @param boolean $withIndex
	 * @return the routed url
	 */
	static function urlRoute1($url, $withIndex=true, $encodeUrl = false) {
		$pos = strpos($url, '?');
		if ($pos === false) {
			return $url;
		}
		
		$url = substr($url, $pos + 1);
		$arrPair = explode('&', $url);
		$arrKeyVal = array();
		foreach ($arrPair as $pair) {
			$key = substr($pair, 0, strpos($pair, '='));
			$val = substr($pair, strpos($pair, '=') + 1);
			$arrKeyVal[$key] = $val;
		}
		$res = new SiteResource();
		$res->setValueFromRequest($arrKeyVal, true);
		return $res->getLink($withIndex, true, $encodeUrl);
	}	
	
	
	
	
	/**
	 * The utility static function for getting the application content everywhere.
	 * NOTE: this static function just try to simulate the system for just running the applycation.
	 * WARNING: be careful when using this function. This may have some strange in the data
	 *
	 * @param string $appName
	 */
	static function getAppContent($appName, $act=null, $task=null, $option=null) {
		if (!SystemSite::checkExistApplication($appName)) {
			return false;
		}
		
		// Store current information
		$curSiteRes = SysRequest::cloneResource();

		// change to the new resource
		$res = &SysRequest::getResource();
		$res->application 	= $appName;
		$res->action		= $act;
		$res->task			= $task;
		$res->option		= $option;
		
		ob_start();
		include SysApplication::getApplicationMainFile ();
		$result = ob_get_contents();
		ob_end_clean();
		
		// restore back the current resource.
		$res = &SysRequest::getResource();
		$res = $curSiteRes;
		
		return $result;
	}
}
?>